<?php
include '../../../wp-blog-header.php';

$url = $_SERVER['HTTP_REFERER'];
$action = $_GET['action'];

wp_get_current_user();
$wp_id = $current_user->ID;

$brand_name_slug = basename($url);
$brand = new Pod('brand');
$brand->findRecords('id DESC', "", "t.brandurl ='$brand_name_slug'");
while ($brand->fetchRecord())
{
    $brand_id = $brand->get_field('id');
}

switch($action)
{
  case 'set':
    $users = new Pod('users');
    $users->findRecords('id DESC', "", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
        $users_tbl_row_id = $users->get_field('id');
        $users_favorite_brands = $users->get_field('favorite_brands.id');
        
        if(!empty($users_favorite_brands))
        {
          if(!is_array($users_favorite_brands))
          {
            $users_favorite_brands = array($users_favorite_brands);
          }
        }
        
        $users_favorite_brands[] = $brand_id;
        $users_favorite_brands = array_unique($users_favorite_brands);
    }
    
    $users_favorite_brands = implode(',',$users_favorite_brands);
    $api = new PodAPI();
    $params = array('datatype' => 'users', 'tbl_row_id' => $users_tbl_row_id, 'columns' => array('favorite_brands'=>$users_favorite_brands));
    $api->save_pod_item($params);
    header("Location:$url");
  break;
  
  case 'unset':
    $users = new Pod('users');
    $users->findRecords('id DESC', "", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
      $users_tbl_row_id = $users->get_field('id');
      $users_favorite_brands = $users->get_field('favorite_brands.id');
    }
    
    if(!empty($users_favorite_brands))
    {
      if(is_array($users_favorite_brands))
      {
        $users_favorite_brands = array_diff($users_favorite_brands, array($brand_id));
        $users_favorite_brands = array_values($users_favorite_brands);
      }
      else
      {
        if($users_favorite_brands == $brand_id)
        {
           $users_favorite_brands = '';
        }
      }
    }

    if(empty($users_favorite_brands))
    {
      $users_favorite_brands = '';
    }
    else
    {
      $users_favorite_brands = implode(',',$users_favorite_brands);
    }
    
    $api = new PodAPI();
    $params = array('datatype' => 'users', 'tbl_row_id' => $users_tbl_row_id, 'columns' => array('favorite_brands'=>$users_favorite_brands));
    $api->save_pod_item($params);
    header("Location:$url");
    break;
}

?>